package com.sxc.study;

import android.os.Build;
import android.util.Log;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.logging.Logger;

/**
 * Create by sunxunchao on 2019/11/19
 */
public class SilentInstallUtil {

    private static final String TAG = SilentInstallUtil.class.getSimpleName();

    /**
     * 执行具体的静默安装逻辑，需要手机ROOT。
     *
     * @param apkPath 要安装的apk文件的路径
     * @return 安装成功返回true，安装失败返回false。
     */
    public static boolean install(String apkPath) {
        boolean result = false;
        DataOutputStream dataOutputStream = null;
        BufferedReader errorStream = null;
        try {
            // 申请su权限
            Process process = Runtime.getRuntime().exec("su");
            dataOutputStream = new DataOutputStream(process.getOutputStream());
            // 执行pm install命令
            String command = "pm install -r " + apkPath + "\n";
            dataOutputStream.write(command.getBytes(Charset.forName("utf-8")));
            dataOutputStream.flush();
            dataOutputStream.writeBytes("exit\n");
            dataOutputStream.flush();
            process.waitFor();
            errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String msg = "";
            String line;
            // 读取命令的执行结果
            while ((line = errorStream.readLine()) != null) {
                msg += line;
            }
            Log.d("TAG", "install msg is " + msg);
            // 如果执行结果中包含Failure字样就认为是安装失败，否则就认为安装成功
            if (!msg.contains("Failure")) {
                result = true;
            }
        } catch (Exception e) {
            Log.e("TAG", e.getMessage(), e);
        } finally {
            try {
                if (dataOutputStream != null) {
                    dataOutputStream.close();
                }
                if (errorStream != null) {
                    errorStream.close();
                }
            } catch (IOException e) {
                Log.e("TAG", e.getMessage(), e);
            }
        }
        return result;
    }

    private static void execLinuxCommand(){
        String cmd= "sleep 2000; am start -n com.sxc.study/com.sxc.study.MainActivity";
        //Runtime对象
        Runtime runtime = Runtime.getRuntime();
        Process localProcess = null;
        try {
            localProcess = runtime.exec(cmd);
        } catch (IOException e) {
            Log.e(TAG, "execLinuxCommand: ", e);
            e.printStackTrace();
        }finally {
            localProcess.destroy();
        }
    }

    public static boolean isRoot() {
        boolean bool = false;
        try {
            bool = new File("/system/bin/su").exists() || new File("/system/xbin/su").exists();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bool;
    }


    public static boolean RootSilentInstall(String pkgName, String pkgPath) {

        boolean result = false;
        Process process = null;
        try {
            String cmd = "pm install -r -i " + pkgName + " --user 0 " + pkgPath;
            process = Runtime.getRuntime().exec(cmd);
//            printMessage(process.getInputStream());
//            printMessage(process.getErrorStream());
//            execLinuxCommand();
            Log.d(TAG, "RootSilentInstall: " + process.getInputStream());
            Log.e(TAG, "RootSilentInstall: " + process.getErrorStream());
            int value = process.waitFor();

            if (value == 0) {
                Log.d(TAG, "RootSilentInstall: success");
                // 代表成功
                result = true;
            } else if (value == 1) {
                Log.d(TAG, "RootSilentInstall: fail");
                // 失败
                result = false;
            } else {
                Log.d(TAG, "RootSilentInstall: none");
                // 未知情况
                result = false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            process.destroy();
        }

        return result;
    }


    public static void install(File apkFile) {
        String cmd = "";
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
//            cmd = "pm install -r -d " + apkFile.getAbsolutePath();
//        } else {
            cmd = "pm install -r  com.nari.casque_control --user 0 " + apkFile.getAbsolutePath();
//        }
        Runtime runtime = Runtime.getRuntime();
        try {
            Process process = runtime.exec(cmd);
            InputStream errorInput = process.getErrorStream();
            InputStream inputStream = process.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String error = "";
            String result = "";
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                result += line;
            }
            bufferedReader = new BufferedReader(new InputStreamReader(errorInput));
            while ((line = bufferedReader.readLine()) != null) {
                error += line;
            }
            Log.d(TAG, "install: " + result);
            Log.d(TAG, "install: error == " + error);
            if(result.equals("Success")){
                Log.i(TAG, "install: Success");
            }else{
                Log.i(TAG, "install: error"+error);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
